package fr.mmt.gisfizz.init;

import fr.mmt.gisfizz.entity.Role;
import fr.mmt.gisfizz.entity.User;
import fr.mmt.gisfizz.repository.RoleRepository;
import fr.mmt.gisfizz.repository.UserRepository;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Init process. <br/>
 *
 * @author Mathieu MAST
 */
@Transactional
@Service
@Slf4j
public class InitProcessImpl implements InitProcess {

    @Resource
    private RoleRepository roleRepository;
    @Resource
    private UserRepository userRepository;

    public @ResponseBody
    @Override
    void init() {
        log.info(" ------ InitProcess ------ ");

        if (0 == roleRepository.count()) {
            log.info(" ------ Load roles and users ------ ");
            
            Role roleUser = new Role();
            roleUser.setCode("ROLE_USER");
            roleUser.setLabel("ROLE_USER");
            roleRepository.save(roleUser);

            Role roleAdmin = new Role();
            roleAdmin.setCode("ROLE_ADMIN");
            roleAdmin.setLabel("ROLE_ADMIN");
            roleRepository.save(roleAdmin);

            User user = new User();
            user.setLogin("user");
            user.setDisplayname("User");
            user.setPassword("user");
            List<Role> userRoles = new ArrayList<>();
            userRoles.add(roleUser);
            user.setRoles(userRoles);
            userRepository.save(user);

            User admin = new User();
            admin.setLogin("admin");
            admin.setDisplayname("Administrator");
            admin.setPassword("admin");
            List<Role> adminRoles = new ArrayList<>();
            adminRoles.add(roleUser);
            adminRoles.add(roleAdmin);
            admin.setRoles(adminRoles);
            userRepository.save(admin);
        }
    }
}
